package vsvm.gui.menus;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;

import vsvm.gui.Environment;
import vsvm.gui.IUpdatable;

public class WindowMenu  extends JMenu implements IUpdatable {
	private final static String MW_CLOSE = "close";
	private final static String MW_TILE = "tile";
	private final static String MW_CASCADE = "cascade";
	private final static String MW_WINDOW = "window";
	
	private JMenuItem miClose = null;
	private JMenuItem miTile = null;
	private JMenuItem miCascade = null;
	
	private class WindowMenuItem extends JMenuItem {
		private JInternalFrame fr;
		
		public WindowMenuItem(String title, JInternalFrame frame) {
			super(title);
			fr = frame;
		}
		
		public JInternalFrame getFrame() {
			return fr;
		}
	}
	
	private class WindowMenuActionListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			if (e.getActionCommand().equals(MW_CLOSE)) {
				Environment.getEnvironment().getMainFrame().getDesktop().closeAll();
				return;
			}
			
			if (e.getActionCommand().equals(MW_TILE)) {
				Environment.getEnvironment().getMainFrame().getDesktop().tile();
				return;
			}
			
			if (e.getActionCommand().equals(MW_CASCADE)) {
				Environment.getEnvironment().getMainFrame().getDesktop().cascade();
				return;
			}
			
			if (e.getActionCommand().equals(MW_WINDOW)) {
				try {
					((WindowMenuItem)e.getSource()).getFrame().setSelected(true);
				} catch (Exception ex) {}
				
			}
		}		
	}
	
	public WindowMenu() {
		super();
		this.setText("Window");
		createItems();		
	}
	
	private void createItems() {
		this.removeAll();
		
		ActionListener ml = new WindowMenuActionListener();
		
		miClose = new JMenuItem("Close all");
		miClose.setActionCommand(MW_CLOSE);
		miClose.addActionListener(ml);
		
		miCascade = new JMenuItem("Cascade");
		miCascade.setActionCommand(MW_CASCADE);
		miCascade.addActionListener(ml);
		
		miTile = new JMenuItem("Tile");
		miTile.setActionCommand(MW_TILE);
		miTile.addActionListener(ml);
		
		this.add(miCascade);
		this.add(miTile);
		this.add(miClose);
		
		if (Environment.getEnvironment().getMainFrame() != null) {
			JDesktopPane d = Environment.getEnvironment().getMainFrame().getDesktop();
			JInternalFrame f[] = d.getAllFrames();
			
			if (f.length > 0) this.add(new JSeparator());
			
			for (int i = 0; i < f.length; i++) {
				WindowMenuItem mi = new WindowMenuItem(f[i].getTitle(), f[i]);
				mi.setActionCommand(MW_WINDOW);
				mi.addActionListener(ml);
				this.add(mi);
				
			}
		}
	}
	
	public void update() {
		createItems();

	}

}
